use anyhow::{anyhow, Result};
use std::process::Command;
use tokio::process::Command as TokioCommand;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use reqwest;

pub struct BrowserSession {
    pub process_id: u32,
}

pub struct BrowserManager {
    pub browser_session: Option<BrowserSession>,
    pub node_script_path: String,
    pub is_running: Arc<AtomicBool>,
    pub server_url: String,
}

impl BrowserManager {
    pub fn new() -> Result<Self> {
        let script_path = std::env::current_dir()?
            .join("scripts")
            .join("browser-server.js");

        Ok(Self {
            browser_session: None,
            node_script_path: script_path.to_string_lossy().to_string(),
            is_running: Arc::new(AtomicBool::new(false)),
            server_url: "http://localhost:3001".to_string(),
        })
    }

    pub async fn initialize(&mut self) -> Result<()> {
        println!("开始初始化Node.js浏览器服务器...");

        // 确保Node.js脚本存在
        if !std::path::Path::new(&self.node_script_path).exists() {
            return Err(anyhow!("Node.js脚本不存在: {}", self.node_script_path));
        }

        // 检查Node.js是否可用
        let node_check = Command::new("node")
            .arg("--version")
            .output();

        match node_check {
            Ok(_) => println!("Node.js可用"),
            Err(_) => return Err(anyhow!("Node.js未安装或不可用")),
        }

        // 启动HTTP服务器
        self.start_server().await?;

        println!("浏览器服务器初始化完成");
        Ok(())
    }

    pub fn is_initialized(&self) -> bool {
        self.is_running.load(Ordering::Relaxed)
    }

    async fn start_server(&mut self) -> Result<()> {
        if self.is_running.load(Ordering::Relaxed) {
            println!("服务器已在运行");
            return Ok(());
        }

        println!("启动浏览器HTTP服务器...");

        // 在后台启动Node.js服务器
        let mut command = TokioCommand::new("node");
        command.arg(&self.node_script_path);

        let child = command.spawn()?;
        
        // 等待服务器启动
        tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;

        // 检查服务器是否启动成功
        let client = reqwest::Client::new();
        let health_url = format!("{}/health", self.server_url);
        
        match client.get(&health_url).timeout(std::time::Duration::from_secs(5)).send().await {
            Ok(response) => {
                if response.status().is_success() {
                    println!("浏览器服务器启动成功");
                    self.is_running.store(true, Ordering::Relaxed);
                    Ok(())
                } else {
                    Err(anyhow!("服务器响应异常: {}", response.status()))
                }
            }
            Err(e) => {
                println!("服务器启动失败: {}", e);
                Err(anyhow!("无法连接到浏览器服务器: {}", e))
            }
        }
    }

    async fn make_request(&self, endpoint: &str) -> Result<String> {
        let client = reqwest::Client::new();
        let url = format!("{}{}", self.server_url, endpoint);
        
        let response = client.get(&url)
            .timeout(std::time::Duration::from_secs(30))
            .send()
            .await?;

        if response.status().is_success() {
            let body = response.text().await?;
            Ok(body)
        } else {
            Err(anyhow!("HTTP请求失败: {}", response.status()))
        }
    }

    pub async fn open_login_page(&self) -> Result<()> {
        println!("通过HTTP调用打开登录页面...");
        
        let result = self.make_request("/open-login").await?;
        println!("服务器响应: {}", result);
        
        // 解析JSON响应
        let response: serde_json::Value = serde_json::from_str(&result)?;
        
        if response.get("success").and_then(|v| v.as_bool()).unwrap_or(false) {
            println!("登录页面已打开");
            Ok(())
        } else {
            let error = response.get("error").and_then(|v| v.as_str()).unwrap_or("未知错误");
            Err(anyhow!("打开登录页面失败: {}", error))
        }
    }

    pub async fn check_login_status(&self) -> Result<bool> {
        println!("通过HTTP调用检查登录状态...");
        
        let result = self.make_request("/check-status").await?;
        println!("服务器响应: {}", result);
        
        // 解析JSON响应
        let response: serde_json::Value = serde_json::from_str(&result)?;
        
        let is_logged_in = response.get("isLoggedIn").and_then(|v| v.as_bool()).unwrap_or(false);
        let message = response.get("message").and_then(|v| v.as_str()).unwrap_or("未知状态");
        
        println!("登录状态: {} ({})", is_logged_in, message);
        Ok(is_logged_in)
    }

    pub async fn get_login_info(&self) -> Result<String> {
        println!("通过HTTP调用获取登录信息...");
        
        let result = self.make_request("/get-info").await?;
        println!("获取到登录信息: {}", result);
        Ok(result)
    }

    pub async fn close(&mut self) -> Result<()> {
        println!("通过HTTP调用关闭浏览器...");

        let _result = self.make_request("/close").await?;
        
        self.browser_session = None;
        self.is_running.store(false, Ordering::Relaxed);
        println!("浏览器已关闭");
        Ok(())
    }
} 